package com.woniuxy.staffservice.web;

import com.woniuxy.staffservice.entity.User;
import com.woniuxy.staffservice.service.UserService;
import commons.DataGridView;
import commons.LayuiJson;
import commons.ResultObj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private LayuiJson layuiJson;

    /**
     * 用户全查询
     */
    @GetMapping("loadAllUser")
    public LayuiJson<User> select(Integer deptid, String deptname, String nickname, String address, Integer page, Integer limit) {

        int index = (page - 1) * limit;
        List<User> users = userService.getByCondition(deptid, deptname, nickname, address, index, limit);
        layuiJson.setCode(0);
        layuiJson.setCount(1000);
        layuiJson.setData(users);
        layuiJson.setMsg("ok");
        return layuiJson;

    }

    /**
     * 根据部门ID查询用户
     */
    @GetMapping("loadUsersByDeptId")
    public DataGridView loadUsersByDeptId(@RequestParam Integer deptId) {
        List<User> users = userService.getByDeptId(deptId);
        return new DataGridView(users);
    }

    /**
     * 增加用户
     */
    @PostMapping("addUser")
    public ResultObj addUser(User user) {
        try {
//            SimpleDateFormat sdf = new SimpleDateFormat();// 格式化时间
//            sdf.applyPattern("yyyy-MM-dd HH:mm:ss");
//            Date date = new Date();// 获取当前时间
//            user.setHiredate(sdf.format(date));
            userService.add(user);
            return ResultObj.ADD_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.ADD_ERROR;
        }
    }

    /**
     * 更新用户
     */
    @PostMapping("updateUser")
    public ResultObj updateUser(User user) {
        try {
            userService.updateById(user);
            return ResultObj.UPDATE_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.UPDATE_ERROR;
        }
    }

    /**
     * 删除用户
     */
    @GetMapping("deleteUser")
    public ResultObj deleteUser(@RequestParam Integer id) {
        try {
            userService.deleteById(id);
            return ResultObj.DELETE_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.DELETE_ERROR;
        }
    }
}
